package com.pilipili.zeus.statistics.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.pilipili.commonutils.Result;
import com.pilipili.zeus.statistics.client.UserClient;
import com.pilipili.zeus.statistics.entity.Daily;
import com.pilipili.zeus.statistics.mapper.DailyMapper;
import com.pilipili.zeus.statistics.service.DailyService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.RandomUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 网站统计日数据 服务实现类
 * 后端查询数据,前端可视化数据
 *
 * @author Unlimited_Blade_Works
 * @since 2021-06-03
 */
@Service
public class DailyServiceImpl extends ServiceImpl<DailyMapper, Daily> implements DailyService {
    @Autowired
    private UserClient userClient;
    @Override
    public void registerCount(String date) {
        QueryWrapper<Daily> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("date_calculated",date);
        baseMapper.delete(queryWrapper);
        Result member = userClient.countRegisterNum(date);
        Integer num = (Integer)member.getData().get("num");
        Daily daily = new Daily();
        daily.setRegisterNum(num);
        daily.setDateCalculated(date);
        daily.setCourseNum(RandomUtils.nextInt(0,999));
        daily.setVideoViewNum(RandomUtils.nextInt(0,999));
        daily.setLoginNum(RandomUtils.nextInt(0,999));
        baseMapper.insert(daily);
    }
    //list集合转为json数组形式的数据返回前端
    @Override
    public Map<String, Object> getData(String type, String begin, String end) {
        QueryWrapper<Daily> queryWrapper = new QueryWrapper<>();
        queryWrapper.between("date_calculated",begin,end);
        queryWrapper.select("date_calculated",type);
        List<Daily> list = baseMapper.selectList(queryWrapper);
        List<String> dateList = new ArrayList<>();
        List<Integer> numList = new ArrayList<>();
        for (Daily daily : list) {
            dateList.add(daily.getDateCalculated());
            switch (type) {
                case "login_num":
                    numList.add(daily.getLoginNum());
                    break;
                case "register_num":
                    numList.add(daily.getRegisterNum());
                    break;
                case "video_view_num":
                    numList.add(daily.getVideoViewNum());
                    break;
                case "course_num":
                    numList.add(daily.getCourseNum());
                    break;
                default:
                    break;
            }
        }
        HashMap<String,Object> map = new HashMap<>();
        map.put("dateList",dateList);
        map.put("numList",numList);
        return map;
    }
}
